<template>
  <div>
    <el-upload
      :action="baseUrl"
      list-type="picture-card"
      :on-preview="handlerPreview"
      :on-remove="onRemove"
      :on-success='onSuccess'
      :on-exceed="onExceed"
      :limit="1"
      :file-list="fileList"
      :before-upload="beforeUpload">
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- <el-dialog :visible.sync="photoDialog" :modal-append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog> -->
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  components: {},
  props: {
    limit:{//上传文件数量，默认为3个
      type:Number,
      default:1
    },
    sort:{
      type:String, //后台需要的参数
      default:'test'
    },
    index:{//外面上传是数组类型传入的下标，不是数组可以不传
      type:Number,
      default:null
    },
    name:{
      type:String,
      default:''
    },
    url:{
      type:String,
      default:''
    }
  },
  computed: {},
  watch: {
    name:function(val,old) {
      if(val == '') {
        console.log(123)
        this.fileList = []
      }
    }
  },
  data() {
    return {
      baseUrl:request.defaults.baseURL + '/sys/uploadFile',
      photoDialog:false,//预览图片弹框，
      dialogImageUrl:'',//预览图片地址
      imageUrl:'',
      fileList: []
    };
  },
  methods: {
    // 案例题图片预览
    handlerPreview(file) {
      this.dialogImageUrl = file.url;
      this.photoDialog = true;
    },
    // 上传成功
    onSuccess( response, file, fileList) {
      if(response.code){
        this.imageUrl = response.data;
      }
      this.$emit('success',response.data)
    },
    onRemove(file, fileList) {
      this.fileList = fileList;
      this.$emit('success',fileList,this.index)
    },
    onExceed(files, fileList) {
      this.$message.warning(`只能上传 ${this.limit} 个文件`);
    },
    // 限制文件上传类型
    beforeUpload(file) {
      let imgArr = ['image/png','image/jpg','image/jpeg','image/gif'];
      const isJPG = file.type ;
      if(imgArr.indexOf(isJPG) == -1){
        this.$message.error('只能上传图片格式!');
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 20MB!');
      }
      return isJPG && isLt2M;
    },

  },
  created() {
    if(this.name != '') {
      let name = this.name.split(',');
      let url = this.url.split(',');
      let arr = url.map((item,index) => {
        if(item.indexOf('http') >-1) {
          return {url:item,name:name[index]}
        }else{
          return {url:config.ip+item,name:name[index]}
        }
       
      });
      this.fileList = arr;
    }else{
      this.fileList = []
    }
  },
  filter: {},
  
};
</script>

<style lang='scss' scoped>

</style>